<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容管理后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .navbar-brand {
            font-weight: 700;
        }
        
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 2rem;
        }
        
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1rem 1.5rem;
        }
        
        .file-item {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .file-item:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .file-preview {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 8px;
        }
        
        .upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 2rem;
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .upload-area:hover,
        .upload-area.drag-over {
            border-color: #667eea;
            background: #e7f3ff;
        }
        
        .btn-gradient {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
        }
        
        .btn-gradient:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
            color: white;
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.15);
        }
        
        .text-editor {
            min-height: 200px;
            background: white;
        }
        
        #editor {
            background: white;
        }
        
        .spinner-border {
            width: 1rem;
            height: 1rem;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="bi bi-gear-fill me-2"></i>
                内容管理后台
            </a>
            
            <div class="navbar-nav ms-auto">
                <button class="btn btn-outline-light btn-sm" onclick="logout()">
                    <i class="bi bi-box-arrow-right me-1"></i>
                    退出登录
                </button>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <ul class="nav nav-pills flex-column" id="nav-tabs">
                            <li class="nav-item">
                                <a class="nav-link active" href="#content-tab" data-bs-toggle="pill">
                                    <i class="bi bi-card-text me-2"></i>
                                    文字内容
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#image-tab" data-bs-toggle="pill">
                                    <i class="bi bi-image me-2"></i>
                                    图片管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#video-tab" data-bs-toggle="pill">
                                    <i class="bi bi-camera-video me-2"></i>
                                    视频管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#settings-tab" data-bs-toggle="pill">
                                    <i class="bi bi-palette me-2"></i>
                                    网站设置
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div class="col-md-9">
                <div class="tab-content">
                    <!-- 文字内容管理 -->
                    <div class="tab-pane fade show active" id="content-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-card-text me-2"></i>
                                    文字内容管理
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <button type="button" class="btn btn-gradient" onclick="addTextBlock()">
                                        <i class="bi bi-plus-circle me-2"></i>
                                        添加文字块
                                    </button>
                                </div>
                                <div id="text-blocks"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图片管理 -->
                    <div class="tab-pane fade" id="image-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-image me-2"></i>
                                    图片管理
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="upload-area" onclick="document.getElementById('imageInput').click()">
                                    <input type="file" id="imageInput" multiple accept="image/*" style="display: none;" onchange="uploadFiles(this, 'image')">
                                    <i class="bi bi-cloud-upload display-4 text-muted"></i>
                                    <p class="mt-2 mb-0">点击或拖拽上传图片</p>
                                    <small class="text-muted">支持 JPG, PNG, GIF 格式</small>
                                </div>
                                <div id="image-list" class="mt-4"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 视频管理 -->
                    <div class="tab-pane fade" id="video-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-camera-video me-2"></i>
                                    视频管理
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="upload-area" onclick="document.getElementById('videoInput').click()">
                                    <input type="file" id="videoInput" multiple accept="video/*" style="display: none;" onchange="uploadFiles(this, 'video')">
                                    <i class="bi bi-camera-video display-4 text-muted"></i>
                                    <p class="mt-2 mb-0">点击或拖拽上传视频</p>
                                    <small class="text-muted">支持 MP4, MOV, AVI 格式</small>
                                </div>
                                <div id="video-list" class="mt-4"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 网站设置 -->
                    <div class="tab-pane fade" id="settings-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-palette me-2"></i>
                                    网站设置
                                </h5>
                            </div>
                            <div class="card-body">
                                <form id="settingsForm">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="siteTitle" class="form-label">网站标题</label>
                                                <input type="text" class="form-control" id="siteTitle" name="title">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="primaryColor" class="form-label">主题色</label>
                                                <input type="color" class="form-control form-control-color" id="primaryColor" name="primaryColor">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="siteDescription" class="form-label">网站描述</label>
                                        <textarea class="form-control" id="siteDescription" name="description" rows="3"></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="backgroundColor" class="form-label">背景色</label>
                                        <input type="color" class="form-control form-control-color" id="backgroundColor" name="backgroundColor">
                                    </div>
                                    
                                    <button type="submit" class="btn btn-gradient">
                                        <i class="bi bi-check-circle me-2"></i>
                                        保存设置
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
    <script>
        let config = {};
        let textEditors = [];

        document.addEventListener('DOMContentLoaded', async () => {
            await loadConfig();
            renderContent();
        });

        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                config = await response.json();
            } catch (error) {
                console.error('加载配置失败:', error);
                showAlert('danger', '加载配置失败');
            }
        }

        function renderContent() {
            renderTextBlocks();
            renderFileList('image');
            renderFileList('video');
            renderSettings();
        }

        function renderTextBlocks() {
            const container = document.getElementById('text-blocks');
            container.innerHTML = '';
            
            const texts = config.content?.texts || [];
            texts.forEach((text, index) => {
                addTextBlock(text.content, index);
            });
            
            if (texts.length === 0) {
                addTextBlock();
            }
        }

        function addTextBlock(content = '', index = -1) {
            const container = document.getElementById('text-blocks');
            const blockId = index >= 0 ? index : Date.now();
            
            const blockDiv = document.createElement('div');
            blockDiv.className = 'mb-4 p-3 border rounded';
            blockDiv.innerHTML = \`
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="mb-0">文字块 \${blockId + 1}</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeTextBlock(this)">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
                <div id="editor-\${blockId}" style="height: 150px;"></div>
            \`;
            
            container.appendChild(blockDiv);
            
            // 初始化富文本编辑器
            const editor = new Quill(\`#editor-\${blockId}\`, {
                theme: 'snow',
                placeholder: '输入文字内容...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        [{'list': 'ordered'}, {'list': 'bullet'}],
                        [{'header': [1, 2, 3, false]}],
                        ['link'],
                        ['clean']
                    ]
                }
            });
            
            if (content) {
                editor.clipboard.dangerouslyPasteHTML(content);
            }
            
            textEditors.push({id: blockId, editor: editor});
        }

        function removeTextBlock(button) {
            const block = button.closest('.mb-4');
            const editorId = block.querySelector('[id^="editor-"]').id.split('-')[1];
            
            // 从编辑器数组中移除
            textEditors = textEditors.filter(item => item.id != editorId);
            
            block.remove();
            saveTextContent();
        }

        async function saveTextContent() {
            const texts = textEditors.map(item => ({
                content: item.editor.root.innerHTML
            }));
            
            try {
                const response = await fetch('/admin/config', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({texts: texts})
                });
                
                const result = await response.json();
                if (result.success) {
                    config.content.texts = texts;
                }
            } catch (error) {
                console.error('保存失败:', error);
            }
        }

        function renderFileList(type) {
            const container = document.getElementById(\`\${type}-list\`);
            const files = config.content?.[type + 's'] || [];
            
            container.innerHTML = '';
            
            files.forEach(file => {
                const fileDiv = document.createElement('div');
                fileDiv.className = 'file-item p-3';
                
                const preview = type === 'image' 
                    ? \`<img src="\${file.path}" class="file-preview" alt="\${file.originalname}">\`
                    : \`<video src="\${file.path}" class="file-preview" muted></video>\`;
                
                fileDiv.innerHTML = \`
                    <div class="row align-items-center">
                        <div class="col-auto">
                            \${preview}
                        </div>
                        <div class="col">
                            <h6 class="mb-1">\${file.originalname}</h6>
                            <small class="text-muted">
                                大小: \${formatFileSize(file.size)} | 
                                上传时间: \${formatDate(file.uploadTime)}
                            </small>
                        </div>
                        <div class="col-auto">
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteFile('\${file.id}')">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                \`;
                
                container.appendChild(fileDiv);
            });
        }

        async function uploadFiles(input, type) {
            const files = input.files;
            if (!files.length) return;
            
            for (let file of files) {
                const formData = new FormData();
                formData.append('file', file);
                
                try {
                    showAlert('info', \`正在上传 \${file.name}...\`);
                    
                    const response = await fetch('/admin/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        // 更新配置
                        if (!config.content[type + 's']) {
                            config.content[type + 's'] = [];
                        }
                        config.content[type + 's'].push(result.file);
                        
                        renderFileList(type);
                        showAlert('success', \`\${file.name} 上传成功\`);
                    } else {
                        showAlert('danger', \`上传失败: \${result.message}\`);
                    }
                } catch (error) {
                    console.error('上传失败:', error);
                    showAlert('danger', \`\${file.name} 上传失败\`);
                }
            }
            
            // 清空input
            input.value = '';
        }

        async function deleteFile(fileId) {
            if (!confirm('确定要删除这个文件吗？')) return;
            
            try {
                const response = await fetch(\`/admin/file/\${fileId}\`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 从配置中移除文件
                    ['images', 'videos'].forEach(type => {
                        if (config.content[type]) {
                            config.content[type] = config.content[type].filter(file => file.id !== fileId);
                        }
                    });
                    
                    renderFileList('image');
                    renderFileList('video');
                    showAlert('success', '文件删除成功');
                } else {
                    showAlert('danger', '删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除失败:', error);
                showAlert('danger', '删除失败');
            }
        }

        function renderSettings() {
            document.getElementById('siteTitle').value = config.title || '';
            document.getElementById('siteDescription').value = config.description || '';
            document.getElementById('primaryColor').value = config.theme?.primaryColor || '#007bff';
            document.getElementById('backgroundColor').value = config.theme?.backgroundColor || '#ffffff';
        }

        document.getElementById('settingsForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const settings = {
                title: formData.get('title'),
                description: formData.get('description'),
                theme: {
                    primaryColor: formData.get('primaryColor'),
                    backgroundColor: formData.get('backgroundColor')
                }
            };
            
            try {
                const response = await fetch('/admin/config', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(settings)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    Object.assign(config, settings);
                    showAlert('success', '设置保存成功');
                } else {
                    showAlert('danger', '保存失败: ' + result.message);
                }
            } catch (error) {
                console.error('保存失败:', error);
                showAlert('danger', '保存失败');
            }
        });

        // 自动保存文字内容
        setInterval(() => {
            if (textEditors.length > 0) {
                saveTextContent();
            }
        }, 10000); // 每10秒自动保存

        async function logout() {
            try {
                await fetch('/admin/logout', {method: 'POST'});
                window.location.href = '/admin/login';
            } catch (error) {
                window.location.href = '/admin/login';
            }
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function formatDate(dateString) {
            return new Date(dateString).toLocaleString('zh-CN');
        }

        function showAlert(type, message) {
            // 简单的toast提示
            const toast = document.createElement('div');
            toast.className = \`alert alert-\${type} position-fixed top-0 end-0 m-3\`;
            toast.style.zIndex = '9999';
            toast.innerHTML = message;
            
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.remove();
            }, 3000);
        }
    </script>
</body>
</html>